<?php
include_once( Foundry::config('libPath').'/fileBucket.class.php' );

class net_mode3_imageBucket_imageModel extends FoundryModel
{
	private $imageBucket	= false;
	
	private $tmpOut			= '/tmp';
	
	protected $hasManyBelongsToMany = array(
		'tags',
	);
	
	protected $afterSave	= 'postSave';
	
	protected $afterFind	= 'postFind';
	
	/**
	 * init()
	 *
	 * init() is called in place of the __construct() method used by the
	 * FoundryModel super class
	 * This function will be called immediately after the __construct method
	 *
	 */ 
	public function init()
	{
		$this->imageBucket = new fileBucket( IMAGEBUCKET_MEDIAPATH );
	}
	
	public function postSave()
	{
		if( $_FILES['imageFile'] && !$_FILES['imageFile']['error']
			&& $this->uid && strpos( $_FILES['imageFile']['type'], 'image' ) !== false ) {

			$fileName = $this->cleanName( $_FILES['imageFile']['name'] );
			$filePath = $_FILES['imageFile']['tmp_name'];

			$tmp = explode( '.', $fileName );
			$ext = array_pop( $tmp );
			
			$thumbName = $this->gd_resizeImage( $filePath, $ext );			
			
			$newThumbName = implode( '.', $tmp ).'_thumb.'.$ext;
			
			$this->imageBucket->save(
				$this->uid,
				$fileName,
				$_FILES['imageFile']['tmp_name']
			);

			$this->imageBucket->save(
				$this->uid,
				$newThumbName,
				$thumbName
			);
			
		}
	}
	
	public function postFind( $data )
	{
		if( !$this->imageBucket ) {
			$this->imageBucket = new fileBucket( IMAGEBUCKET_MEDIAPATH );
		}
		
		for( $i=0; $i<count($data); $i++ ) {
			if( $data[$i]['uid'] ) {
				$data[$i]['filePathSystem'] = $this->imageBucket->retrieve(
					$data[$i]['uid'] );
				$data[$i]['filePath'] = IMAGEBUCKET_MEDIAPATH_WEB.'/'.
					$this->imageBucket->retrieve(
						$data[$i]['uid'], true );
						
				$tmp = explode( '.', $data[$i]['name'] );
				$ext = array_pop( $tmp );
				$thumb = implode( '.', $tmp ).'_thumb.'.$ext;
						
				$data[$i]['thumbNail'] = $thumb;
			}
		}
	}
	
	private function gd_resizeImage( $fileName, $ext = 'jpg' )
	{
		// The file
		$filename = $fileName;
		
		// Set a maximum height and width
		$width = 150;
		$height = 150;
		
		// Get new dimensions
		list($width_orig, $height_orig) = getimagesize($filename);
		
		$ratio_orig = $width_orig/$height_orig;
		
		if( ( $width/$height ) > $ratio_orig ) {
		 $width = $height*$ratio_orig;
		} else {
		 $height = $width/$ratio_orig;
		}

		
		// Resample
		$image_p = imagecreatetruecolor($width, $height);
		if( $ext == 'png' ) {
			$image = imagecreatefrompng( $filename );
		} elseif( $ext == 'gif' ) {
			$image = imagecreatefromgif( $filename );
		} else {
			$image = imagecreatefromjpeg($filename);
		}
		imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
		
		// Output
		$outFile = $this->tmpOut.'/'.md5($fileName).'.'.$ext;
		
		if( $ext == 'png' ) {
			imagepng( $image_p, $outFile, 100 );
		} elseif( $ext == 'gif' ) {
			imagegif( $image_p, $outFile, 100 );
		} else {
			imagejpeg($image_p, $outFile, 100);
		}
		
		return $outFile;
	}
	
	public function gd_rotateImage( $fileName, $degrees )
	{
		$tmp = explode( '.', $fileName );
		$ext = strtolower( array_pop( $tmp ) );

		if( $ext == 'png' ) {
			
			$source = imagecreatefrompng( $fileName );
			
			// Rotate
			$rotate = imagerotate( $source, $degrees, 0 );
			
			// Output
			imagepng( $rotate, $fileName, 100 );
		} elseif( $ext == 'gif' ) {
			
			$source = imagecreatefromgif( $fileName );
			
			// Rotate
			$rotate = imagerotate( $source, $degrees, 0 );
			
			// Output
			imagegif( $rotate, $fileName, 100 );
		} else {
			$source = imagecreatefromjpeg( $fileName );
			
			// Rotate
			$rotate = imagerotate( $source, $degrees, 0 );
			
			// Output
			imagejpeg( $rotate, $fileName, 100 );
		}

	}
	
	public function cleanName( $str )
	{
		$str = str_replace( ' ', '_', $str );
		$str = preg_replace( '/[^a-zA-Z0-9\-_\.]/', '', $str );
		
		return $str;
	}
	
	public function getCategoryTags()
	{
		$sql = 'select '.$this->nameSpace.'tags.uid, '.$this->nameSpace.
			'tags.name from '.$this->nameSpace.'tags, '.$this->nameSpace.
			'tagsMap where '.$this->nameSpace.'tags.uid = '.$this->nameSpace.
			'tagsMap.tag_id and net_mode3_imageBucket_image_id > 0 group by '.
			$this->nameSpace.'tags.uid';

		$stmt = $this->dbh->prepare( $sql );
		$stmt->execute();
		
		$row = $stmt->fetchAll();
		
		return $row;
	}
	
	public function findByTag( $tag, $start )
	{
		if( $tag ) {
			
			$sql = 'select * from net_mode3_imageBucket_image left join '.
				$this->nameSpace.'tagsMap on '.$this->nameSpace.
				'tagsMap.net_mode3_imageBucket_image_id = '.
				'net_mode3_imageBucket_image.uid where '.$this->nameSpace.
				'tagsMap.tag_id = :tg group by net_mode3_imageBucket_image.uid';

			$stmt = $this->dbh->prepare( $sql );
			$stmt->bindParam( ':tg', $tag );
			
			$stmt->execute();
			
			$class = get_class( $this );		
	
			$all = $stmt->fetchAll();

			$this->postFind( &$all );
			
			return $all;
		
		}
		
		return false;
	}

}

?>